import {Menu, Icon} from 'antd'
// import Menu from '../../_antd1.11.2/menu';
// import Icon from '../../_antd1.11.2/icon';
const SubMenu = Menu.SubMenu;
const ItemMenu = Menu.Item;
import WeaScroll from '../wea-scroll';
import cloneDeep from 'lodash/cloneDeep';
import objectAssign from 'object-assign';

class WeaMenuInline extends React.Component {
    constructor(props) {
		super(props);
        const openKeys = this.getOpenKeys(props.defaultSelectedKey,props.datas);
        //console.log("openKeys1:",openKeys);
        this.state = {
            mode:props.mode || "Inline",
            datas:props.datas || [],
            inlineWidth: props.inlineWidth || 197,
            verticalWidth: props.verticalWidth || 61,
            openKeys:openKeys || [],
            selectedKey:props.defaultSelectedKey || "", //包含SubMenu，只做单选
            defaultSelectedKey:props.defaultSelectedKey || "", //包含SubMenu，只做单选
            canClick: true,
        }
    }
    shouldComponentUpdate(nextProps) {
        //  if(JSON.stringify(this.props.datas) !== JSON.stringify(nextProps.datas)  || (this.props.defaultSelectedKey !== nextProps.defaultSelectedKey&&this.state.defaultSelectedKey !== nextProps.defaultSelectedKey)) {
        //      return true;
        //  }
         return true;
    }
    componentWillReceiveProps(nextProps) {
    	//console.log('datas:',this.props.datas,nextProps.datas,this.props.datas.toString() !== nextProps.datas.toString());
    	//console.log('defaultSelectedKey',this.props.defaultSelectedKey,nextProps.defaultSelectedKey,this.props.defaultSelectedKey !== nextProps.defaultSelectedKey);
    	//console.log('defaultSelectedKey',this.state.defaultSelectedKey,nextProps.defaultSelectedKey,this.state.defaultSelectedKey !== nextProps.defaultSelectedKey);

         if(JSON.stringify(this.props.datas) !== JSON.stringify(nextProps.datas)  || (this.props.defaultSelectedKey !== nextProps.defaultSelectedKey && this.state.defaultSelectedKey !== nextProps.defaultSelectedKey)) {
            //计算出openKeys
            let newProps = {
                datas:nextProps.datas || [],
                defaultSelectedKey:nextProps.defaultSelectedKey || "",
                selectedKey:nextProps.defaultSelectedKey || ""
            };
            //if(this.props.defaultSelectedKey !== nextProps.defaultSelectedKey&&this.state.defaultSelectedKey !== nextProps.defaultSelectedKey)
            //    newProps.openKeys = this.getOpenKeys(nextProps.defaultSelectedKey,nextProps.datas);
            this.setState(newProps);
        }
    }
    componentDidMount(){
    	//解决IE8之类不支持getElementsByClassName
//		if (!document.getElementsByClassName) {
//		    document.getElementsByClassName = function (className, element) {
//		        var children = (element || document).getElementsByTagName('*');
//		        var elements = new Array();
//		        for (var i = 0; i < children.length; i++) {
//		            var child = children[i];
//		            var classNames = child.className.split(' ');
//		            for (var j = 0; j < classNames.length; j++) {
//		                if (classNames[j] == className) {
//		                    elements.push(child);
//		                    break;
//		                }
//		            }
//		        }
//		        return elements;
//		    };
//		}
//  	let spanOuts = document.getElementsByClassName('wea-menu-tip-out');
//  	if(spanOuts.length > 0){
//  		for (let i = 0; i < spanOuts.length; i++) {
//  			let spanInner = document.getElementsByClassName('wea-menu-tip-inner')[i];
//  			if(spanInner.offsetWidth < spanOuts[i].offsetWidth){
//  				spanOuts[i].title = '';
//  			}
//  		}
//  	}
    }
    render() {
        const {mode,datas,inlineWidth,verticalWidth} = this.state;
        const {openKeys,selectedKey,defaultSelectedKey} = this.state;
        let style = {width:inlineWidth};
        let that = this;
        return (
                <Menu
                    openAnimation={()=>{}}
                    inlineIndent={verticalWidth / 2 - 9}
                    mode={mode}
                    openKeys={openKeys}
                    selectedKeys={[]}
                    onOpen={(e)=>{that.changeOpen(e.openKeys)}}
                    onClose={(e)=>{that.changeOpen(e.openKeys)}}
                    onClick={(e)=>{that.changeSelectedKey(e.key,that.getDataByKey(e.key,datas),0)}} >
                    {this.renderMenuItem(datas,1)}
                </Menu>
        )
    }
//          <div className="wea-menu wea-menu-inline" style={style}>
//              <div className="wea-menu-switch" onClick={this.onModeChange.bind(this)}><Icon type={mode == "vertical" ? "menu-unfold" : "menu-fold"} /></div>
//              <WeaScroll className="wea-scroll" typeClass="scrollbar-macosx" conClass="wea-menu-inline" conHeightNum={40}>
//              </WeaScroll>
//          </div>
    getOpenKeys(key,datas) {
       const data = this.getDataByKey(key,datas);
       const treeKey = data.treeKey;
       let treeKeyArr = treeKey?treeKey.split("{$}"):[];
       //console.log("treeKey:",treeKey," treeKeyArr:",treeKeyArr);
       return treeKeyArr;
    }
    onModeChange() {
        const {mode} = this.state;
        if(typeof this.props.onModeChange=="function") {
            this.props.onModeChange(mode);
        }
    }
    getDataByKey(key,datas) {
        let that = this;
        let obj = "";
        for(let i=0;i<datas.length&&obj=="";i++) {
            if(datas[i].id==key) {
                obj = cloneDeep(datas[i]);
            }
            if(obj==""&&datas[i].child&&datas[i].child.length>0) {
                obj = that.getDataByKey(key,datas[i].child);
            }
        }
        return obj;
    }
    changeSelectedKey(key,data,type) {
    	const {canClick} = this.state;
        const {clickBlock} = this.props;
    	const that = this;
//  	let d = new Date();
//  	console.log(canClick,d.getTime());
    	if(canClick){
	        this.setState({
	        	canClick:false,
	            selectedKey:key
	        });
	        if(typeof this.props.onSelect=="function") {
	            this.props.onSelect(key,data,type);
	        }
	        setTimeout(()=>{that.setState({canClick:true})},!!clickBlock ? clickBlock : 300);
    	}
    }
    changeOpen(openKeys) {
        this.setState({
            openKeys:openKeys
        });
    }
    renderMenuItem(datas,level) {
        const selectedClassName = "wea-menu-selected";
        let that = this;
        const {selectedKey,canClick} = this.state;
        let datasArr = new Array();
        for(let i=0;i<datas.length;i++) {
        	const data = datas[i];
            const isSubMenu = data.child && data.child.length>0;
            const isSelected = selectedKey==data.id||"verTop_"+selectedKey==data.id;
            if(data.isInlineHide !== 'true'){
	            if(isSubMenu) {
	                datasArr.push(
	                    <SubMenu
	                    	disabled={!canClick}
	                        selectedClassName={isSelected?selectedClassName:""}
	                        key={data.id}
	                        onTitleClick={(e)=>{that.changeSelectedKey(e.key,data,0)}}
	                        title={that.renderTitle(data,level)}>
	                        {that.renderMenuItem(data.child,level+1)}
	                    </SubMenu>
	                )
	            }
	            else {
	                datasArr.push(
	                    <ItemMenu
	                        className={isSelected?selectedClassName:""}
	                        key={data.id}>
	                        {that.renderTitle(data,level)}
	                    </ItemMenu>
	                )
	            }
            }
        }
        return datasArr;
    }
    renderTitle(data,level) {
    	const {verticalWidth,tipVisible} = this.state;
    	const that = this;
        const needImg = level==1;
        const showImg = needImg && data.icon && data.icon!="";
        const underLineStyle = data.hasUnderLine == 'true' ? {borderBottom:'1px solid #bbb'} : {};
        const topLineStyle = data.hasTopLine == 'true' ? {borderTop:'1px solid #bbb'} : {};
        const borderStyle = objectAssign({height:42,position:'relative'}, underLineStyle, topLineStyle);
        const iconMarginR = verticalWidth / 2 - 9;

        const img = showImg?(<img style={{verticalAlign:"middle",marginRight:iconMarginR}} align="middle" src={data.icon} alt={data.name} width="18px" height="18px" />):(
                    <i style={{fontSize:"18px",verticalAlign:"middle",marginRight:iconMarginR}} className={"wevicon wevicon-menu-default" + " " + "wevicon-menu-" + data.levelid} />)
        const urlIcon = <img className='wea-titleUrlIcon' style={{position:'absolute',right:20,top:13}} align="middle" src={data.titleUrlIcon} width="16px" height="16px" onClick={(e)=>{that.changeSelectedKey(e.key,data,1);e.stopPropagation()}}/>;
        return (
        	<div style={borderStyle}>
                <span title={data.name} className='wea-menu-tip-out'>
	                {needImg?img:""}
	                {!!data.tagColor ? <span style={{display:"inline-block",width:10,height:10,verticalAlign:"middle",border:"1px solid #bbb",backgroundColor:data.tagColor}}></span> : ""}
	                <span className='wea-menu-tip-inner' style={needImg?{}:{marginLeft:12}}>{data.name}</span>
                </span>
	            {!!data.titleUrlIcon ? urlIcon : ""}
        	</div>
        )
    }
}


export default WeaMenuInline